package com.smartscreen.attendancemanage.service.impl;

import com.smartscreen.attendancemanage.dto.StudentInfoDTO;
import com.smartscreen.attendancemanage.service.StudentInfoService;
import com.smartscreen.baseinfomanage.client.BaseInfoClient;
import com.smartscreen.common.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StudentInfoServiceImpl implements StudentInfoService {
    
    @Autowired
    private BaseInfoClient baseInfoClient;
    
    @Override
    @Cacheable(value = "students", key = "#studentIds.toString()")
    public Map<String, StudentInfoDTO> getStudentsBatch(List<String> studentIds) {
        if (studentIds == null || studentIds.isEmpty()) {
            return new HashMap<>();
        }
        
        try {
            Map<String, Map<String, Object>> studentDataMap = baseInfoClient.getStudentsBatch(studentIds);
            
            Map<String, StudentInfoDTO> result = new HashMap<>();
            for (Map.Entry<String, Map<String, Object>> entry : studentDataMap.entrySet()) {
                String studentId = entry.getKey();
                Map<String, Object> studentData = entry.getValue();
                
                StudentInfoDTO dto = new StudentInfoDTO();
                dto.setStudentId((String) studentData.get("studentId"));
                dto.setName((String) studentData.get("name"));
                dto.setStudentNumber((String) studentData.get("studentNumber"));
                
                result.put(studentId, dto);
            }
            
            return result;
        } catch (Exception e) {
            // 记录日志并返回空Map
            System.err.println("获取学生信息失败: " + e.getMessage());
            return new HashMap<>();
        }
    }
    
    @Override
    @Cacheable(value = "classStudents", key = "#classId")
    public List<String> getStudentIdsByClassId(String classId) {
        try {
            ApiResponse<List<String>> response = baseInfoClient.getStudentIdsByClassId(classId);
            return response.getData() != null ? response.getData() : new ArrayList<>();
        } catch (Exception e) {
            System.err.println("获取班级学生ID列表失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    
    @Override
    @Cacheable(value = "student", key = "#studentId")
    public StudentInfoDTO getStudentInfo(String studentId) {
        Map<String, StudentInfoDTO> students = getStudentsBatch(Arrays.asList(studentId));
        return students.get(studentId);
    }
}